#!/usr/bin/python
# -*- coding: UTF-8 -*-

from sqlalchemy import *
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import *
import pandas as pd

class prestoEngine:
    presto_ip='master'
    presto_port='8085'
    presto_hive_catalog='hive'
    presto_table_schema='parquet'

    def __init__(self,ip=presto_ip,port=presto_port,catalog=presto_hive_catalog,schema=presto_table_schema):
        self.presto_ip=ip
        self.presto_port=port
        self.presto_hive_catalog=catalog
        self.presto_table_schema=schema
        # pass

    def get_connection_str(self):
        engine_str1 = 'presto://'+self.presto_ip+':'+self.presto_port+'/'+self.presto_hive_catalog+'/'+self.presto_table_schema
        # engine_str1='hive://'+self.presto_ip+':'+self.presto_port+'/'+self.presto_hive_catalog

        print('presto server path:'+engine_str1)
        return engine_str1


    def build_engine(self):
        engine_str=self.get_connection_str()        
        engine = create_engine(engine_str,encoding='utf-8')  
        return (engine,self)


    def query(self,sql_str):
        df = pd.read_sql_query(sql_str, engine) 
        return df 


    def q(self,sql_str):        
        # engine=self.build_engine()   # 放外面否则每次query都需要实例化
        df = pd.read_sql_query(sql_str, engine) 
        return df 
 


#解决查询语句中有中文无法查询的情况
import os
import sys
import posixpath
import urllib

if sys.getdefaultencoding() != 'utf-8':
   # reload(sys)
   sys.setdefaultencoding('utf-8')



(engine,presto)=prestoEngine().build_engine()


#from prestoEngine import presto 调用方式 
# presto.query(xxx) 



df=presto.query("""select * from ai.ae_chuzhi limit 10""")
df















# if __name__ == '__main__':
# # 支持各种初始化（各种参数配置）
    # engine = prestoEngine()
    # engine = prestoEngine('master')
    # engine = prestoEngine('master','8085')
    # engine = prestoEngine(ip='master',schema='parquet')
#     df=engine.query('select * from ods.drg_drg_zd_data  limit 10')
#     print(df)


# from prestoEngine import engine  调用方式  engine().query(xxxx)
# def engine():
#     return prestoEngine()  

#from prestoEngine import *    调用方式  m=prestoEngine()  m.query(xxxxx)